const sql = require('mssql');
/**
 * 
 * 拣货区域分配管理
 */

/**
 * 
 * 获取人员信息 
 */
const getStaffInfo = async (ctx, next) => {
    const body = ctx.request.body;
    let selectSql = `SELECT * FROM ( SELECT ROW_NUMBER() OVER(ORDER BY Q.area DESC) AS px,Y.BM,Y.MC,Y.GW,Y.DLMC,Q.area,Q.status FROM BM_YG Y 
    LEFT JOIN YG_QYFP Q ON Y.BM = Q.BM WHERE QY_FLAG = 'T' `;
    let totalSql = ` SELECT COUNT(Y.BM) AS TOTAL FROM BM_YG Y WHERE QY_FLAG = 'T' `;
    let searchSqlList = [];
    if (body.searchVal.BM.val) {
        searchSqlList.push(` AND (Y.MC LIKE '%${body.searchVal.BM.val}%' OR Y.DLMC LIKE '%${body.searchVal.BM.val}%'  )`);
    }

    selectSql += ` ${searchSqlList.join(' ')})AS t1 WHERE  t1.px between ${(body.pageNum - 1) * 10 + 1} and ${body.pageNum * 10} `;
    totalSql += searchSqlList.join(' ');
    let result = await sql.query(selectSql);
    let total = await sql.query(totalSql);
    ctx.body = { result: result.recordset, total: total.recordset[0].TOTAL }

}

/**
 * 
 * 给员工分配区域 
 */
const addDistributionArea = async (ctx, next) => {
    const body = ctx.request.body;
    let isExist = await sql.query(`SELECT COUNT(BM) AS PX  FROM YG_QYFP WHERE BM = '${body.BM}' `);
    let actionSql = '';
    if (isExist.recordset[0] && isExist.recordset[0].PX > 0) {
        actionSql = `UPDATE YG_QYFP SET status = '${body.status}',area = ${body.area}  WHERE  BM = '${body.BM}' `;
    } else {
        actionSql = `INSERT INTO YG_QYFP VALUES ('${body.BM}',${body.area},'${body.status}')`;
    }
    let result = await sql.query(actionSql);
    if (result.rowsAffected[0] > 0) {
        ctx.body = { success: true }
    } else {
        ctx.body = { success: false }
    }

}





module.exports = {
    'POST /getStaffInfo': getStaffInfo,
    'POST /addDistributionArea': addDistributionArea,
}